package com.sq.partner.manager.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayAuwConfig;
import com.sq.partner.manager.mybatis.model.GatewayAuwProd;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NlifeProd;
import com.sq.partner.manager.mybatis.model.RiskAlgMap;
import com.sq.partner.manager.mybatis.model.TradFeeRateAmnt;
import com.sq.partner.manager.mybatis.model.TradFeeRateDay;
import com.sq.partner.manager.mybatis.model.TradFeeRateFixed;
import com.sq.partner.manager.mybatis.model.TradFeeRateMonth;
import com.sq.partner.manager.mybatis.model.TradFeeRiskCommon;
import com.sq.partner.manager.mybatis.model.TradProdInst;
import com.sq.partner.manager.mybatis.model.TradeFeeCov;
import com.sq.partner.manager.service.FeeRateService;
import com.sq.partner.manager.service.IGatewayProductService;
import com.sq.partner.manager.service.INlifeProdConfigService;
import com.sq.partner.manager.service.TreddeFeeCovService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
import com.sq.partner.manager.util.excel.ImportExcelBuilderTool;
import com.sq.partner.manager.util.excel.ImportExcelEntity;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

@Controller
@RequestMapping(value = "/product/feeRate")
public class FeeRateController {

	private static Logger logger = LogUtil.getLog(FeeRateController.class);

	@Resource
	private IGatewayProductService iGatewayProductService;

	@Resource
	private FeeRateService feeRateService;

	@Resource
	ImportExcelBuilderTool importExcelBuilderTool;

	@Resource
	private TreddeFeeCovService tradeFeeCovService;
	
	@Resource
	private INlifeProdConfigService nProductService;
	/**
	 * 加载算法配置table的数据
	 * @param prodCode
	 * @param calDefId
	 * @param tradPlanCode
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/loadTableInfo")
	public Map<String, Object> loadTableInfo(String prodCode, String calDefId, String childCalDefId, String tradPlanCode) throws Exception {
		if (StrUtil.isEmpty(prodCode)) {
			return null;
		}

		Map<String, Object> data = new HashMap<String, Object>();

		if ("0000000001".equals(calDefId)) {// 险种天数算法
			TradProdInst tradProdInst = iGatewayProductService.queryTradProdInstById(prodCode);
			data.put("tradProdInst", tradProdInst);
			TradFeeRateDay tradFeeRateDay = new TradFeeRateDay();
			tradFeeRateDay.setRiskCode(tradPlanCode);
			List<TradFeeRateDay> feeList = feeRateService.queryTradFeeRateDay(tradFeeRateDay);
			data.put("feeList", feeList);
		} else if ("0000000003".equals(calDefId)) {// 险种月数算法
			TradProdInst tradProdInst = iGatewayProductService.queryTradProdInstById(prodCode);
			data.put("tradProdInst", tradProdInst);
			TradFeeRateMonth tradFeeRateMonth = new TradFeeRateMonth();
			tradFeeRateMonth.setRiskCode(tradPlanCode);
			List<TradFeeRateMonth> feeList = feeRateService.queryTradFeeRateMonth(tradFeeRateMonth);
			data.put("feeList", feeList);
		} else if ("0000000002".equals(calDefId)) {// 固定保费算法
			List<TradFeeRateFixed> feeList = feeRateService.queryTradFeeRateFixedById(tradPlanCode);
			data.put("feeList", feeList);
		} else if ("0000000004".equals(calDefId)) { // 保额计算保费
			List<TradFeeRateAmnt> feeList = feeRateService.queryTradFeeRateRateAmntById(tradPlanCode);
			data.put("feeList", feeList);
		} else if ("0000000006".equals(calDefId)) {// 险种通用算法
			if ("000000000605".equals(childCalDefId)) {// 座位区间
				List<Map<String, Object>> list = feeRateService.queryTradFeeRiskCommonByRiskCode(tradPlanCode);
				for (Map<String, Object> map : list) {
					String cond7 = map.get("COND7").toString();
					cond7 = changeCond7CodeToName(cond7);
					map.put("COND7STR", cond7);
				}
				data.put("feeList", list);
				return data;
			} else if ("000000000602".equals(childCalDefId) || "000000000603".equals(childCalDefId)) {// 整车/每座
				List<Map<String, Object>> list = feeRateService.queryTradFeeRiskCommonByRiskCode(tradPlanCode);
				for (Map<String, Object> map : list) {
					String cond7 = map.get("COND7").toString();
					cond7 = changeCond7CodeToName(cond7);
					map.put("COND7STR", cond7);
				}
				data.put("feeList", list);
				return data;
			}else if("000000000606".equals(childCalDefId)){//每天保费乘以天数算法
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("riskCode", tradPlanCode);
				List<TradFeeRiskCommon> feeList = feeRateService.queryTradFeeRiskCommonByMap(map);
				data.put("feeList", feeList);
			}
		}
		return data;
	}
	/**
	 * 新意见险检验算法对应的方案是否出单
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/checkOpenCalDiv1")
	public int checkOpenCalDiv1(String prodCode) throws Exception{
		return tradeFeeCovService.checkInsure(prodCode);
	}
	/**
	 * 新意见险保存和更新核保规则
	 * @param tradProdCode
	 * @param auwConfigListStr
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/setAuwConfigsToProd1")
	public Result setAuwConfigsToProd1(String tradProdCode, String auwConfigListStr) {
		List<GatewayAuwProd> list = new ArrayList<GatewayAuwProd>();
		GatewayAuwProd auwProd = null;
		String transCode = "CIC001";

		if (StrUtil.isNotEmpty(auwConfigListStr) && !"''".equals(auwConfigListStr)) {
			try {
				feeRateService.removeAllAuwConfigsFromProd(tradProdCode);
			} catch (Exception e) {
				logger.error("删除该产品的核保规则失败", e);
				return Result.success("设置失败");
			}
			String ids = "";
			if (!StrUtil.isEmpty(auwConfigListStr)) {
				// 创建一个JsonParser
				JsonParser parser = new JsonParser();
				// 通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
				JsonElement el = parser.parse(auwConfigListStr);
				// 把JsonElement对象转换成JsonArray
				JsonArray jsonArray = null;
				if (el.isJsonArray()) {
					jsonArray = el.getAsJsonArray();
				}
				for (JsonElement jsonElement : jsonArray) {
					String id = jsonElement.getAsJsonObject().get("id").getAsString();
					ids = ids + id + ",";
				}
				if (ids.length() > 0) {
					ids = ids.substring(0, ids.length() - 1);
				}
			}
			String[] auwArr = ids.split(",");
			for (int i = 0; i < auwArr.length; i++) {
				auwProd = new GatewayAuwProd();
				auwProd.setConfigId(Long.parseLong(auwArr[i]));  
				auwProd.setTradProdCode(tradProdCode);
				auwProd.setTransCode(transCode);
				list.add(auwProd);
			}
			try {
				feeRateService.batchInsertIntoFeeRate("insertGatewayAuwProd", list);
				return Result.success("设置成功");
			} catch (Exception e) {
				logger.error("保存产品核保规则失败", e);
				return Result.success("设置失败");
			}
		} else {
			try {
				feeRateService.removeAllAuwConfigsFromProd(tradProdCode);
				return Result.success("核保规则重置成功");
			} catch (Exception e) {
				logger.error("删除该产品的核保规则失败", e);
				return Result.success("核保规则重置失败");
			}
		}
	}

	/***
	 * 新意见险保费计算方式
	 * @param tradeFeeCov
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/saveCall1")
	@ResponseBody
	public Map<String,Object> saveCall(String fixedConds, String days,String prodCode,String riskCode,String covId,String fixed,String callId,String cond7,String rationId,HttpServletRequest request){
		HttpSession session = request.getSession(); 
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		Map<String, Object> map=new HashMap<String, Object>();
		//封装实体
		map.put("riskCode", riskCode);
		map.put("coveCode", covId);
		map.put("prodCode", prodCode);
		map.put("rationId", rationId);
		List<TradeFeeCov> treCovs =new ArrayList<TradeFeeCov>();
		//判断算法
		if("000000000801".equals(callId)||"000000000809".equals(callId)||"000000000814".equals(callId)){
			/***删除已配置的算法**/
			try {
					/*tradeFeeCovService.deleteTradeCov(map);*/
					TradeFeeCov treCov=new TradeFeeCov();
					treCov.setCoveCode(covId);
					treCov.setProdCode(prodCode);
					treCov.setPremRate(new BigDecimal(fixed));
					treCov.setRiskCode(riskCode);
					treCov.setOprateCode(user.getUserCode());
					treCov.setOprateTime(new Date());
					treCov.setRationId(rationId);
					map.put("result", true);
					treCovs.add(treCov);
					feeRateService.addNlifeBatchFeeRate(treCovs, map);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
			//按天区间
		}else if("000000000802".equals(callId)){
			/**解析days*/
			List<Map<String,String>> list = JsonUtils.parseJson(days, ArrayList.class);	
			System.out.println(list);
			for (Map<String, String> map2 : list) {
				//查询当前最大id
				TradeFeeCov treCov=new TradeFeeCov();
				treCov.setCond1(map2.get("cond1"));
				treCov.setCond2(map2.get("cond2"));
				treCov.setCoveCode(covId);
				treCov.setProdCode(prodCode);
				treCov.setPremRate(new BigDecimal(map2.get("preRate")));
				treCov.setRiskCode(riskCode);
				treCov.setOprateCode(user.getUserCode());
				treCov.setOprateTime(new Date());
				treCov.setRationId(rationId);
				treCovs.add(treCov);
			}
			try {
				/***判断天区间是否正确*/
				Collections.sort(treCovs,new Comparator(){
					@Override
					public int compare(Object o1, Object o2) {
						int flag=0;
						TradeFeeCov trade1=(TradeFeeCov) o1;
						TradeFeeCov trade2=(TradeFeeCov) o2;
						int  a = Integer.parseInt(trade1.getCond1());
						int  b = Integer.parseInt(trade2.getCond1());
						if(a<b){
							flag= -1;
						}
						if(a>b){
							flag= 1;
						}
						return flag;
					}
				});
				
				for (int i = 0; i <treCovs.size(); i++) {
					if(i==0){
						continue;
					}
					Integer min=Integer.parseInt(treCovs.get(i).getCond1());
					Integer max=Integer.parseInt(treCovs.get(i-1).getCond2());
					if(min<max){
						map.put("result", false);
						map.put("massager", "天区间存在重复请检查后保存");
						return map;
					}
				}
				/*tradeFeeCovService.deleteTradeCov(map);
				feeRateService.batchInsertIntoFeeRate("inserttradeFeeCovNewLifeBach", treCovs);*/
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
			//麻醉类型算保费
		}else if("000000000803".equals(callId)){
			try {
			/*	tradeFeeCovService.deleteTradeCov(map);*/
				TradeFeeCov treCov=new TradeFeeCov();
				treCov.setPremRate(new BigDecimal(fixed));
				treCov.setCond7(cond7);
				treCov.setCoveCode(covId);
				treCov.setProdCode(prodCode);
				treCov.setRiskCode(riskCode);
				treCov.setOprateCode( user.getUserCode());
				treCov.setOprateTime(new Date());
				treCov.setRationId(rationId);
				treCovs.add(treCov);
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
			// 手术类型算法，麻醉类型算法
		} else if ("000000000886".equals(callId) || "000000000887".equals(callId)) {
			try {
				ObjectMapper mapper = new ObjectMapper();
				Map<String, String> fixedMap = mapper.readValue(fixedConds, Map.class);
				Set<String> fixedCondsKeys = fixedMap.keySet();
				for (String fixedCondsKey : fixedCondsKeys) {
					TradeFeeCov treCov = new TradeFeeCov();
					treCov.setPremRate(new BigDecimal(fixedMap.get(fixedCondsKey)));
					treCov.setCond7(fixedCondsKey);
					treCov.setCoveCode(covId);
					treCov.setProdCode(prodCode);
					treCov.setRiskCode(riskCode);
					treCov.setOprateCode(user.getUserCode());
					treCov.setOprateTime(new Date());
					treCov.setRationId(rationId);
					treCovs.add(treCov);
				}
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
			/**责任保额算法*/
		}else if("000000000804".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			System.out.println(list);
			/*tradeFeeCovService.deleteTradeCov(map);*/
			try {
				for (Map<String, Object> map2 : list) {
					//查询当前最大id
					TradeFeeCov treCov=new TradeFeeCov();
				/*	Double d=(Double) ;*/
					if(StrUtil.isNotEmpty((String) map2.get("cond1"))){
						treCov.setCond1((String) map2.get("cond1"));
					}
					treCov.setCoveCode(covId);
					treCov.setProdCode(prodCode);
					treCov.setPremRate(new BigDecimal(map2.get("preRate").toString()));
					if(StrUtil.isNotEmpty((String)map2.get("cond5"))){
						treCov.setCond5(new BigDecimal(map2.get("cond5").toString()));
					}
					treCov.setRiskCode(riskCode);
					treCov.setOprateCode(user.getUserCode());
					treCov.setOprateTime(new Date());
					treCov.setRationId(rationId);
					treCovs.add(treCov);
				}
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
		/**责任贷款金额保费算法  界面不显示*/
		}else if("000000000805".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			System.out.println(list);
			tradeFeeCovService.deleteTradeCov(map);
			for (Map<String, Object> map2 : list) {
				//查询当前最大id
				TradeFeeCov treCov=new TradeFeeCov();
				treCov.setDays(Integer.parseInt(map2.get("miny").toString()));
				treCov.setCoveCode(covId);
				treCov.setProdCode(prodCode);
				treCov.setMaxdays(Integer.parseInt(map2.get("maxy").toString()));
				treCov.setPremRate(new BigDecimal(map2.get("preRate").toString()));
				treCov.setCodeCname(map2.get("dept").toString());
				treCov.setRiskCode(riskCode);
				treCov.setOprateCode(user.getUserCode());
				treCov.setOprateTime(new Date());
				treCov.setRationId(rationId);
				treCovs.add(treCov);
			}
			System.out.println("----------------------------------------------------------"+treCovs);
			try {
				feeRateService.batchInsertIntoFeeRate("inserttradeFeeCovNewLifeBach2", treCovs);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
			/**驾乘险责任算法*/
		}else if("000000000806".equals(callId)||"000000000815".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			System.out.println(list);
			/*tradeFeeCovService.deleteTradeCov(map);*/
			for (Map<String, Object> map2 : list) {
				TradeFeeCov treCov=new TradeFeeCov();
				/**座位数*/
				if(!"0".equals(map2.get("cond1").toString())){
					treCov.setCond1(map2.get("cond1").toString());
				};
				treCov.setCoveCode(covId);
				treCov.setProdCode(prodCode);
				/**车辆类型*/
				if(!"0".equals(map2.get("cond8").toString())){
					treCov.setCond8(map2.get("cond8").toString());
				}
				treCov.setPremRate(new BigDecimal(map2.get("fixed").toString()));
				/**车辆使用性质*/
				if(!"0".equals(map2.get("cond7").toString())){
					treCov.setCond7(map2.get("cond7").toString());
				}
				treCov.setRiskCode(riskCode);
				treCov.setOprateCode(user.getUserCode());
				treCov.setOprateTime(new Date());
				treCov.setRationId(rationId);
				treCovs.add(treCov);
			}
			System.out.println("----------------------------------------------------------"+treCovs);
			try {
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
			/**责任按年龄区间算法*/
		}else if("000000000807".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			System.out.println(list);
			/*tradeFeeCovService.deleteTradeCov(map);*/
			for (Map<String, Object> map2 : list) {
				//查询当前最大id
				TradeFeeCov treCov=new TradeFeeCov();
				/**最小年龄*/
				treCov.setCond11(map2.get("cond11").toString());
				treCov.setCoveCode(covId);
				treCov.setProdCode(prodCode);
				/**最大年龄*/
				treCov.setCond12(map2.get("cond12").toString());
				treCov.setPremRate(new BigDecimal(map2.get("preRate").toString()));
				treCov.setRiskCode(riskCode);
				treCov.setOprateCode(user.getUserCode());
				treCov.setOprateTime(new Date());
				treCov.setRationId(rationId);
				treCovs.add(treCov);
			}
			System.out.println("----------------------------------------------------------"+treCovs);
			try {
				/*feeRateService.batchInsertIntoFeeRate("inserttradeFeeCovNewLifeBach4", treCovs);*/
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
		/**驾乘险座位区间算法*/
		}else if("000000000810".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			System.out.println(list);
			/*tradeFeeCovService.deleteTradeCov(map);*/
			for (Map<String, Object> map2 : list) {
				//查询当前最大id
				TradeFeeCov treCov=new TradeFeeCov();
				/**座位数下限*/
				if(!"0".equals(map2.get("cond1").toString())&&StrUtil.isNotEmpty(map2.get("cond1").toString())){
					treCov.setCond1(map2.get("cond1").toString());
				};
				/***座位数上线*/
				if(!"0".equals(map2.get("cond2").toString())&&StrUtil.isNotEmpty(map2.get("cond2").toString())){
					treCov.setCond2(map2.get("cond2").toString());
				};
				treCov.setCoveCode(covId);
				treCov.setProdCode(prodCode);
				/**车辆类型**/
				if(!"0".equals(map2.get("cond8").toString())){
					treCov.setCond8(map2.get("cond8").toString());
				}
				treCov.setPremRate(new BigDecimal(map2.get("fixed").toString()));
				/**使用性质*/
				if(!"0".equals(map2.get("cond7").toString())){
					treCov.setCond7(map2.get("cond7").toString());
				}
				treCov.setRiskCode(riskCode);
				treCov.setOprateCode(user.getUserCode());
				treCov.setOprateTime(new Date());
				treCov.setRationId(rationId);
				treCovs.add(treCov);
			}
			System.out.println("----------------------------------------------------------"+treCovs);
			try {
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				/*feeRateService.batchInsertIntoFeeRate("inserttradeFeeCovNewLifeBach3", treCovs);*/
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
		}
		/**按天按月算法*/
		else if("000000000813".equals(callId)||"000000000812".equals(callId)){

			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			/*System.out.println(list);*/
		/*	tradeFeeCovService.deleteTradeCov(map);*/
			try {
				for (Map<String, Object> map2 : list) {
					//查询当前最大id
					TradeFeeCov treCov=new TradeFeeCov();
					/**天数/月数/年数*/
					treCov.setCond1((String) map2.get("cond1"));
					treCov.setCoveCode(covId);
					treCov.setProdCode(prodCode);
					treCov.setPremRate(new BigDecimal(map2.get("preRate").toString()));
					treCov.setRiskCode(riskCode);
					treCov.setOprateCode(user.getUserCode());
					treCov.setOprateTime(new Date());
					treCov.setRationId(rationId);
					treCovs.add(treCov);
				}
				/*feeRateService.batchInsertIntoFeeRate("inserttradeFeeCovNewLifeBach1", treCovs);*/
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
			//麻醉类型算保费
		/**信保通算法*/
		}else if ("000000000877".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			
			try {
				for (Map<String, Object> map2 : list) {
					//查询当前最大id
					TradeFeeCov treCov=new TradeFeeCov();
					/*treCov.setDays(Integer.parseInt((String) map2.get("days")));*/
					treCov.setCoveCode(covId);
					treCov.setProdCode(prodCode);
					treCov.setPremRate(new BigDecimal(map2.get("preRate").toString()).divide(new BigDecimal(1000)));
					treCov.setRiskCode(riskCode);
					treCov.setCond1(map2.get("cond1").toString());
					treCov.setCond2(map2.get("cond2").toString());
					treCov.setCond3(map2.get("cond3").toString());
					treCov.setCond7(map2.get("cond7").toString());
					treCov.setCond10(map2.get("cond10").toString());
					treCov.setOprateCode(user.getUserCode());
					treCov.setOprateTime(new Date());
					treCov.setRationId(rationId);
					treCovs.add(treCov);
				}
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
		}
		//责任按年龄区间-分期算法
		else if("000000000884".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			for (Map<String, Object> map2 : list) {
				TradeFeeCov treCov = null;
				//分期
				if ("1".equals(map2.get("isByStaged").toString())) {
					Map<String, List<Map<String, String>>> monthMap = (Map<String, List<Map<String, String>>>) map2.get("monthMap");
					List<Map<String, String>> monthList = monthMap.get("elements");
					for (int i = 0; i < monthList.size(); i++) {
						treCov=new TradeFeeCov();
						Map<String, String> map3 = monthList.get(i);
						treCov.setCond4(new BigDecimal(map3.get("value")));
						treCov.setCond3(map3.get("key").split("month")[1]);
						//是否分期
						treCov.setCond2(map2.get("isByStaged").toString());
						/**最小年龄*/
						treCov.setCond11(map2.get("cond11").toString());
						treCov.setCoveCode(covId);
						treCov.setProdCode(prodCode);
						/**最大年龄*/
						treCov.setCond12(map2.get("cond12").toString());
						treCov.setRiskCode(riskCode);
						treCov.setOprateCode(user.getUserCode());
						treCov.setOprateTime(new Date());
						treCov.setRationId(rationId);
						treCovs.add(treCov);
					}
				}else{
					treCov=new TradeFeeCov();
					treCov.setPremRate(new BigDecimal(map2.get("preRate").toString()));
					//是否分期
					treCov.setCond2(map2.get("isByStaged").toString());
					/**最小年龄*/
					treCov.setCond11(map2.get("cond11").toString());
					treCov.setCoveCode(covId);
					treCov.setProdCode(prodCode);
					/**最大年龄*/
					treCov.setCond12(map2.get("cond12").toString());
					treCov.setRiskCode(riskCode);
					treCov.setOprateCode(user.getUserCode());
					treCov.setOprateTime(new Date());
					treCov.setRationId(rationId);
					treCovs.add(treCov);
				}
			}
			System.out.println("----------------------------------------------------------"+treCovs);
			try {
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
		}
		//责任固定保费-分期算法
		else if("000000000885".equals(callId)){
			/**解析days*/
			List<Map<String,Object>> list = JsonUtils.parseJson(days, ArrayList.class);	
			for (Map<String, Object> map2 : list) {
				TradeFeeCov treCov = null;
				//分期
				if ("1".equals(map2.get("isByStaged").toString())) {
					Map<String, List<Map<String, String>>> monthMap = (Map<String, List<Map<String, String>>>) map2.get("monthMap");
					List<Map<String, String>> monthList = monthMap.get("elements");
					for (int i = 0; i < monthList.size(); i++) {
						treCov=new TradeFeeCov();
						Map<String, String> map3 = monthList.get(i);
						treCov.setCond4(new BigDecimal(map3.get("value")));
						treCov.setCond3(map3.get("key").split("month")[1]);
						//是否分期
						treCov.setCond2(map2.get("isByStaged").toString());
						treCov.setCoveCode(covId);
						treCov.setProdCode(prodCode);
						treCov.setRiskCode(riskCode);
						treCov.setOprateCode(user.getUserCode());
						treCov.setOprateTime(new Date());
						treCov.setRationId(rationId);
						treCovs.add(treCov);
					}
				}else{
					treCov=new TradeFeeCov();
					treCov.setPremRate(new BigDecimal(map2.get("preRate").toString()));
					//是否分期
					treCov.setCond2(map2.get("isByStaged").toString());
					treCov.setCoveCode(covId);
					treCov.setProdCode(prodCode);
					treCov.setRiskCode(riskCode);
					treCov.setOprateCode(user.getUserCode());
					treCov.setOprateTime(new Date());
					treCov.setRationId(rationId);
					treCovs.add(treCov);
				}
			}
			System.out.println("----------------------------------------------------------"+treCovs);
			try {
				feeRateService.addNlifeBatchFeeRate(treCovs, map);
				map.put("result", true);
			} catch (Exception e) {
				map.put("result", false);
				logger.error("算法配置出现异常，请联系管理员", e);
			}
		}
		return map;
	}
	
	/***
	 * 新意见险查询已配置的算法
	 */
	@RequestMapping(value="/getCall")
	@ResponseBody
	public Map<String,Object> getCall(String prodCode,String riskCode,String covId,String calDefIdAll,String rationId){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("riskCode", riskCode);
		map.put("coveCode", covId);
		map.put("prodCode", prodCode);
		map.put("rationId", rationId);
		try {
			 List<TradeFeeCov> list= tradeFeeCovService.getTradeFeeCov(map);
			 /**麻醉类型*/
			 List<DictDto> dictDtos= DictCache.getDict(Constants.DICT_NLIFE_ELECODETYPE);
			 // 手术类型
             List<DictDto> dictDtos3= DictCache.getDict(Constants.DICT_NLIFE_OPS);
			 /**车辆类型*/
			 List<DictDto> dictDtos1= DictCache.getDict(Constants.DICT_NLIFE_CARTYPE);
			 /**算法规则*/
			 List<DictDto> dictDtos2= DictCache.getDict(Constants.DICT_CALL_TYPE);
			 if("000000000877".equals(calDefIdAll)&&list!=null){
				 for (int i = 0; i < list.size(); i++) {
					 list.get(i).setPremRate(list.get(i).getPremRate().multiply(new BigDecimal(1000)));
				} 
			 }
			 map.put("calls", list);
			 map.put("codeCnames",dictDtos);
			 map.put("carType", dictDtos1);
			 map.put("callTypes", dictDtos2);
			 map.put("opsTypes", dictDtos3);
			 if("000000000806".equals(calDefIdAll)||"000000000815".equals(calDefIdAll)||"000000000810".equals(calDefIdAll)){
				 if(list!=null){
				 for (int i = 0; i < list.size(); i++) {
					 list.get(i).setCHNname(changeCond7CodeToName1(list.get(i).getCodeCname()));
					} 
				 }
			 }
			 if ("000000000884".equals(calDefIdAll)&&list!=null) {
			 		List<String> newList = new ArrayList<String>();
			 		for (TradeFeeCov tradeFeeCov : list) {
						if (!newList.contains(tradeFeeCov.getMinAge()+","+tradeFeeCov.getMaxAge())) {
							newList.add(tradeFeeCov.getMinAge()+","+tradeFeeCov.getMaxAge());
						}
					}
			 		ArrayList<Map<String, Object>> stagedList = new ArrayList<Map<String, Object>>();
			 		for (String age : newList) {
			 			String[] ageArr = age.split(",");
						Map<String, Object> stagedMap1 = new HashMap<String, Object>();
						String[] monthNum  = new String[12];

						for (TradeFeeCov  tradeFeeCov: list) {
							if ("0".equals(tradeFeeCov.getCond2())&&tradeFeeCov.getCond11().equals(ageArr[0])&&tradeFeeCov.getCond12().equals(ageArr[1])) {
								Map<String, Object> BigMap = new HashMap<String, Object>();
								Map<String, Object> stagedMap = new HashMap<String, Object>();
								stagedMap.put("isByStaged", "0");
								stagedMap.put("fixed", tradeFeeCov.getPremRate());
								BigMap.put("age", age);
								BigMap.put("stagedMap", stagedMap);
								stagedList.add(BigMap);
							}else if("1".equals(tradeFeeCov.getCond2())&&tradeFeeCov.getCond11().equals(ageArr[0])&&tradeFeeCov.getCond12().equals(ageArr[1])) {
								for (int j = 0; j < 12; j++) {
									if (tradeFeeCov.getCond3().equals((j+1)+"")) {
										 monthNum[j] = tradeFeeCov.getCond4().toString();
									}
								}
							}
						}
						String monthApp = "";
						for (int i = 0; i < monthNum.length; i++) {
							if (i==monthNum.length-1) {
								monthApp += monthNum[i];
							}else{
								monthApp += monthNum[i]+",";
							}
						}
						if (!monthApp.contains("null")) {
							Map<String, Object> BigMap = new HashMap<String, Object>();
							stagedMap1.put("isByStaged", "1");
							stagedMap1.put("month", monthApp);
							BigMap.put("age", age);
							BigMap.put("stagedMap", stagedMap1);
							stagedList.add(BigMap);
						}
					}
			 		map.put("stagedList", stagedList);
		 		}
			 
			 if ("000000000885".equals(calDefIdAll)&&list!=null) {
			 		ArrayList<Map<String, Object>> stagedList = new ArrayList<Map<String, Object>>();
					Map<String, Object> stagedMap1 = new HashMap<String, Object>();
					String[] monthNum  = new String[12];
					for (TradeFeeCov  tradeFeeCov: list) {
						if ("0".equals(tradeFeeCov.getCond2())) {
							Map<String, Object> BigMap = new HashMap<String, Object>();
							Map<String, Object> stagedMap = new HashMap<String, Object>();
							stagedMap.put("isByStaged", "0");
							stagedMap.put("fixed", tradeFeeCov.getPremRate());
							BigMap.put("stagedMap", stagedMap);
							stagedList.add(BigMap);
						}else if("1".equals(tradeFeeCov.getCond2())) {
							for (int j = 0; j < 12; j++) {
								if (tradeFeeCov.getCond3().equals((j+1)+"")) {
									 monthNum[j] = tradeFeeCov.getCond4().toString();
								}
							}
						}
					}
					String monthApp = "";
					for (int i = 0; i < monthNum.length; i++) {
						if (i==monthNum.length-1) {
							monthApp += monthNum[i];
						}else{
							monthApp += monthNum[i]+",";
						}
					}
					if (!monthApp.contains("null")) {
						Map<String, Object> BigMap = new HashMap<String, Object>();
						stagedMap1.put("isByStaged", "1");
						stagedMap1.put("month", monthApp);
						BigMap.put("stagedMap", stagedMap1);
						stagedList.add(BigMap);
					}
			 		map.put("stagedList", stagedList);
		 		}
			 
			 
			 /**配置的产品信息*/
			NlifeProd tradProdInst = nProductService.queryProdInfoById(prodCode);
			String remark=tradeFeeCovService.getRemark(calDefIdAll);
			map.put("tradProd", tradProdInst);
			map.put("remark",remark);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("异常，请联系管理员", e);
		}
		return map;
	}
	/**
	 * 新意见险算法模板下载
	 * @param session
	 * @param response
	 * @param calDefId
	 * @throws Exception
	 */
	@RequestMapping(value = "/newLifeDownLoad")
	public  void newLifeDownLoad(HttpSession session,HttpServletResponse response,String calDefId) throws Exception{
		File myFile=null;
		ServletOutputStream outPutStream=null;
		InputStream inputStream=null;
		String fileN = "天数算法";
		if("000000000813".equals(calDefId)){
			fileN = "责任按天算法";
		}else if("000000000812".equals(calDefId)){
			fileN = "责任按月算法";
		}else if("000000000804".equals(calDefId)){
			fileN = "责任保额算法";
		}else if("000000000877".equals(calDefId)){
			fileN = "信保通算法";
		}
		String fileCode = calDefId;
		String root = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		String path = root.substring(0, root.indexOf("WEB-INF"))+"template"+File.separator+"newlifeCal"+File.separator+calDefId+".xls";
		 try{
			 myFile=new File(path); 
			 if(myFile.exists()){
				 String fileName=java.net.URLEncoder.encode(fileN+".xls","UTF-8");  
				 response.setHeader("Content-disposition","attachment; filename="+ fileName);  
				 response.setContentType("application/x-download"); 
		         outPutStream=response.getOutputStream();  
		         inputStream=new  BufferedInputStream(new FileInputStream(myFile));  
		         byte[] bytes=new byte[10240];
		         int len = 0;
		         while((len = inputStream.read(bytes)) != -1)  
		         {    
		             outPutStream.write(bytes,0,len);   
		         } 
		         outPutStream.flush();
			  }
		    }catch(IOException e){
		    	logger.info("算法模板文件不存在",e);
		  }finally{
			  if(inputStream!=null){
				  inputStream.close();
			  }
			  if(outPutStream!=null){
				  outPutStream.close();
			  }
		  }
	}

	/**
	 * 导入算法
	 * @param reconciliationFile
	 * @param response
	 * @param session
	 * @param calDefId
	 * @param tradProdCode
	 * @throws Exception
	 */
	@RequestMapping(value = "/calTemplateImport1")
	public void calTemplateImport1(@RequestParam MultipartFile reconciliationFile,HttpServletResponse response, HttpSession session,String calDefId,String prodCode) throws Exception {
		InputStream input = null;
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		Page<String>  page = new Page<String>();
		PrintWriter out = null;
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		 /**算法规则*/
		List<DictDto> dictDtos2= DictCache.getDict(Constants.DICT_CALL_TYPE);
		for (DictDto dictDto : dictDtos2) {
			map.put(dictDto.getCodeName(),dictDto.getCode());
		}
		map.put("信保通", 1);
		map.put("农贷通", 0);
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			input = reconciliationFile.getInputStream();
			ImportExcelEntity entity= new ImportExcelEntity();
			if ("000000000802".equals(calDefId)){//天数excel处理
				entity.setColumnName("cond1,cond2,premRate");
				entity.setColumnValidateRule("2,2,2");
				entity.setExtraValidateRule("20_0_");
			}else if("000000000804".equals(calDefId)){
				entity.setColumnName("cond1,cond5,premRate");
				entity.setColumnValidateRule("2,2,2");
				entity.setExtraValidateRule("20_0_");
			}else if("000000000813".equals(calDefId)||"000000000812".equals(calDefId)){
				entity.setColumnName("cond1,premRate");
				entity.setColumnValidateRule("2,2");
				entity.setExtraValidateRule("20_0_");
			}else if("000000000877".equals(calDefId)){
				entity.setColumnName("cond3,cond7,premRate,cond1,cond2,cond10");
				entity.setColumnValidateRule("0,2,2,0,0,0");
			}
			List<Map<String,Object>> excelLists = importExcelBuilderTool.parseExcel(input, entity);
			if(excelLists != null && excelLists.size()>0){
				/**信保通需转换格式name为code*/
				if("000000000877".equals(calDefId)){
					for (Map<String, Object> map2 : excelLists) {
						map2.put("cond3", map.get(map2.get("cond3")));
						map2.put("cond10", map.get(map2.get("cond10")));
						dataMap.put("callTypes", dictDtos2);
					}
				}
				 /**配置的产品信息*/
				NlifeProd tradProdInst = nProductService.queryProdInfoById(prodCode);
				dataMap.put("tradProd", tradProdInst);
				dataMap.put("calls", excelLists);
			}else{
				//抛出异常 excel为空
				page.setResult("error");
				page.setMessage("Excel内容为空，请录入数据");
				dataMap.put("result", false);
			}		
			dataMap.put("result", true);
		} catch (AppException a) {
			logger.info("---------Excel导入失败");
			dataMap.put("result", false);
		}catch (Exception e) {
			logger.info("---------Excel导入失败");
			dataMap.put("result", false);
		}finally {
			out.write(JsonUtils.toJson(dataMap));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}

	/**
	 * 保存和更新算法配置信息
	 * @param arr
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/saveCal")
	public String saveCal(@RequestBody List<Map<String, Object>> arr,HttpSession session) {

		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		
		String tradPlanCode = (String) arr.get(0).get("value");
		String calDefId = (String) arr.get(1).get("value");
		String childCalDefId = (String) arr.get(2).get("value");
		RiskAlgMap riskAlgMap = new RiskAlgMap();
		riskAlgMap.setOperatorsName(user.getUserCode());
		riskAlgMap.setTradPlanCode(tradPlanCode);
		riskAlgMap.setOperatorTime(new Date());
		
		if ("0000000001".equals(calDefId)) {// 险种天数算法
			try {
				List<TradFeeRateDay> list = (List<TradFeeRateDay>) feeRateService.getDataListForDayOrMonth(arr);
				feeRateService.deleteTradFeeRateDayByRiskCode(tradPlanCode);
				feeRateService.batchInsertIntoFeeRate("insertTradFeeRateDay", list);
				feeRateService.updateOps(riskAlgMap);
				return "{\"result\":true}";
			} catch (Exception e) {
				logger.error("险种天数算法表数据插入失败", e);
				return "{\"result\":false}";
			}
		} else if ("0000000003".equals(calDefId)) {// 险种月数算法
			try {
				List<TradFeeRateMonth> list = (List<TradFeeRateMonth>) feeRateService.getDataListForDayOrMonth(arr);
				feeRateService.deleteTradFeeRateMonthByRiskCode(tradPlanCode);
				feeRateService.batchInsertIntoFeeRate("insertTradFeeRateMonth", list);
				feeRateService.updateOps(riskAlgMap);
				return "{\"result\":true}";
			} catch (Exception e) {
				logger.error("险种月数算法表数据插入失败", e);
				return "{\"result\":false}";
			}
		} else if ("0000000002".equals(calDefId)) {// 固定保费算法
			TradFeeRateFixed feeRateFixed = new TradFeeRateFixed();
			BigDecimal premRate = new BigDecimal(arr.get(2).get("value").toString());
			feeRateFixed.setRiskCode(tradPlanCode);
			feeRateFixed.setPremRate(premRate);
			try {
				feeRateService.delTradFeeRateFixedById(tradPlanCode);
				feeRateService.insertTradFeeRateFixed(feeRateFixed);
				feeRateService.updateOps(riskAlgMap);
				return "{\"result\":true}";
			} catch (Exception e) {
				logger.error("固定保费算法数据插入失败", e);
				return "{\"result\":false}";
			}
		} else if ("0000000004".equals(calDefId)) {// 保额计算保费算法
			TradFeeRateAmnt tradFeeRateAmnt = new TradFeeRateAmnt();
			tradFeeRateAmnt.setRiskCode(tradPlanCode);
			tradFeeRateAmnt.setPartnerNo((String) arr.get(2).get("value"));
			tradFeeRateAmnt.setDeptNo((String) arr.get(3).get("value"));
			BigDecimal yearRate = new BigDecimal((String) arr.get(4).get("value"));
			tradFeeRateAmnt.setYearRate(yearRate);
			try {
				feeRateService.delTradFeeRateAmntById(tradPlanCode);
				feeRateService.insertTradFeeRateAmnt(tradFeeRateAmnt);
				feeRateService.updateOps(riskAlgMap);
				return "{\"result\":true}";
			} catch (Exception e) {
				logger.error("保额计算保费算法数据插入失败", e);
				return "{\"result\":false}";
			}
		} else if ("0000000006".equals(calDefId)) {//险种通用算法
			if("000000000606".equals(childCalDefId)){//每天保费固定乘以天数
				try {
					feeRateService.delTradFeeRiskCommonByRiskCode(tradPlanCode);
					long maxId=feeRateService.queryMaxId();
					TradFeeRiskCommon tradFeeRiskCommon = new TradFeeRiskCommon();
					tradFeeRiskCommon.setId(maxId+1);
					tradFeeRiskCommon.setRiskCode(tradPlanCode);
					BigDecimal premRate = new BigDecimal((String) arr.get(3).get("value"));
					tradFeeRiskCommon.setPremRate(premRate);
					feeRateService.insertTradFeeRiskCommon(tradFeeRiskCommon);
					feeRateService.updateOps(riskAlgMap);
					return "{\"result\":true}";
				} catch (Exception e) {
					logger.error("每天保费固定乘以天数算法数据插入失败", e);
					return "{\"result\":false}";
				}
			} else if ("000000000605".equals(childCalDefId)) {// 险种通用算法  驾乘险座位区间
				List<TradFeeRiskCommon> list;
				try {
					list = feeRateService.getDataListForTradFeeRiskCommon(arr);
					feeRateService.delTradFeeRiskCommonByRiskCode(tradPlanCode);
					boolean flag = feeRateService.batchInsertIntoRiskCommon(list);
					feeRateService.updateOps(riskAlgMap);
					if (flag) {
						return "{\"result\":true}";
					} else {
						return "{\"result\":false}";
					}
				} catch (Exception e) {
					logger.error("险种通用算法配置出现异常，请联系管理员", e);
					return "{\"result\":false}";
				}
			} else if ("000000000602".equals(childCalDefId) || "000000000603".equals(childCalDefId)) {// 整车/每座
				List<TradFeeRiskCommon> list;
				try {
					list = feeRateService.getDataListForTradFeeRiskCommon(arr);
					feeRateService.delTradFeeRiskCommonByRiskCode(tradPlanCode);
					boolean flag = feeRateService.batchInsertIntoRiskCommon(list);
					feeRateService.updateOps(riskAlgMap);
					if (flag) {
						return "{\"result\":true}";
					} else {
						return "{\"result\":false}";
					}
				} catch (Exception e) {
					logger.error("险种通用算法配置出现异常，请联系管理员", e);
					return "{\"result\":false}";
				}
			}
		}
		return "{\"result\":false}";
	}

	// 加载合作伙伴
	@RequestMapping(value = "/queryChannelInfoOfLife")
	public @ResponseBody Page<GatewayChannelInfo> queryChannelInfoOfLife(HttpSession session, Integer size, Integer pageIndex, String channelCode,
			String channelName) throws Exception {
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelName(channelName);
		channelInfo.setChannelCode(channelCode);
		GatewayUser gatewayuser = (GatewayUser) session.getAttribute(Constants.SESSION_USER);
		page.setDepts(gatewayuser.getDepts());
		page.setType(channelInfo);
		Page<GatewayChannelInfo> p = feeRateService.queryPageForGatewayChannelInfo(page);
		return p;
	}

	// 加载出单机构
	@RequestMapping(value = "/loadCoreDept")
	public @ResponseBody Page<CoreDept> queryAllCoreDepts(Integer size, Integer pageIndex, String deptCode, String deptCNname, String channelCode)
			throws Exception {
		Page<CoreDept> page = new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept = new CoreDept();
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCNname);
		page.setType(dept);
		Page<CoreDept> page2 = feeRateService.queryPageForCoreDept(page, channelCode);
		return page2;
	}

	/**
	 * 分页查询所有的核保规则
	 * @param tradProdCode
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/queryAuwConfigsByPage")
	public Page<GatewayAuwConfig> queryAuwConfigsByPage(int size, int pageIndex, String tradProdCode) throws Exception {
		return feeRateService.queryAuwConfigsByPage(size, pageIndex, tradProdCode);
	}

	/**
	 * 查询该产品已经配置的核保规则
	 * @param tradProdCode
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/queryAuwConfigsByProd")
	public List<GatewayAuwProd> queryAuwConfigsByProd(String tradProdCode) throws Exception {
		return feeRateService.queryAuwConfigsByProd(tradProdCode);
	}

	/**
	 * 保存和更新核保规则
	 * @param tradProdCode
	 * @param auwConfigListStr
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/setAuwConfigsToProd")
	public Result setAuwConfigsToProd(String tradProdCode, String auwConfigListStr) {
		List<GatewayAuwProd> list = new ArrayList<GatewayAuwProd>();
		GatewayAuwProd auwProd = null;
		String transCode = "1010,1021";

		if (StrUtil.isNotEmpty(auwConfigListStr) && !"''".equals(auwConfigListStr)) {
			try {
				feeRateService.removeAllAuwConfigsFromProd(tradProdCode);
			} catch (Exception e) {
				logger.error("删除该产品的核保规则失败", e);
				return Result.success("设置失败");
			}
			String ids = "";
			if (!StrUtil.isEmpty(auwConfigListStr)) {
				// 创建一个JsonParser
				JsonParser parser = new JsonParser();
				// 通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
				JsonElement el = parser.parse(auwConfigListStr);
				// 把JsonElement对象转换成JsonArray
				JsonArray jsonArray = null;
				if (el.isJsonArray()) {
					jsonArray = el.getAsJsonArray();
				}
				for (JsonElement jsonElement : jsonArray) {
					String id = jsonElement.getAsJsonObject().get("id").getAsString();
					ids = ids + id + ",";
				}
				if (ids.length() > 0) {
					ids = ids.substring(0, ids.length() - 1);
				}
			}
			String[] auwArr = ids.split(",");
			for (int i = 0; i < auwArr.length; i++) {
				auwProd = new GatewayAuwProd();
				auwProd.setConfigId(Long.parseLong(auwArr[i]));
				auwProd.setTradProdCode(tradProdCode);
				auwProd.setTransCode(transCode);
				list.add(auwProd);
			}
			try {
				feeRateService.batchInsertIntoFeeRate("insertGatewayAuwProd", list);
				return Result.success("设置成功");
			} catch (Exception e) {
				logger.error("保存产品核保规则失败", e);
				return Result.success("设置失败");
			}
		} else {
			try {
				feeRateService.removeAllAuwConfigsFromProd(tradProdCode);
				return Result.success("核保规则重置成功");
			} catch (Exception e) {
				logger.error("删除该产品的核保规则失败", e);
				return Result.success("核保规则重置失败");
			}
		}
	}

	/**
	 * 算法模板下载
	 * @param session
	 * @param response
	 * @param calDefId
	 * @throws Exception
	 */
	@RequestMapping(value = "/calTemplateDownLoad")
	public  void calTemplateDownLoad(HttpSession session,HttpServletResponse response,String calDefId,String childCalDefId) throws Exception{
		File myFile=null;
		ServletOutputStream outPutStream=null;
		InputStream inputStream=null;
		String fileN = "";
		String fileCode = calDefId;
		if ("0000000001".equals(calDefId)) {
			fileN = "天数算法";
		} else if ("0000000003".equals(calDefId)) {
			fileN = "月数算法";
		}else if("0000000006".equals(calDefId)){
			fileCode = childCalDefId;
			if("000000000602".equals(childCalDefId)){
				fileN = "驾乘险每座算法";
			}else if("000000000603".equals(childCalDefId)){
				fileN = "驾乘险整车算法";
			}else if("000000000605".equals(childCalDefId)){
				fileN = "驾乘险座位区间算法";
			}
		}
		String root = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		String path = root.substring(0, root.indexOf("WEB-INF"))+"template"+File.separator+"lifeCal"+File.separator+fileCode+".xls";
		 try{
			 myFile=new File(path); 
			 if(myFile.exists()){
				 String fileName=java.net.URLEncoder.encode(fileN+".xls","UTF-8");  
				 response.setHeader("Content-disposition","attachment; filename="+ fileName);  
				 response.setContentType("application/x-download"); 
		         outPutStream=response.getOutputStream();  
		         inputStream=new  BufferedInputStream(new FileInputStream(myFile));  
		         byte[] bytes=new byte[10240];
		         int len = 0;
		         while((len = inputStream.read(bytes)) != -1)  
		         {    
		             outPutStream.write(bytes,0,len);   
		         } 
		         outPutStream.flush();
			  }
		    }catch(IOException e){
		    	logger.info("算法模板文件不存在",e);
		  }finally{
			  if(inputStream!=null){
				  inputStream.close();
			  }
			  if(outPutStream!=null){
				  outPutStream.close();
			  }
		  }
	}

	/**
	 * 导入算法
	 * @param reconciliationFile
	 * @param response
	 * @param session
	 * @param calDefId
	 * @param tradProdCode
	 * @throws Exception
	 */
	@RequestMapping(value = "/calTemplateImport")
	public void calTemplateImport(@RequestParam MultipartFile reconciliationFile,HttpServletResponse response, HttpSession session,String calDefId,String tradProdCode,String childCalDefId) throws Exception {
		InputStream input = null;
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		Page<String>  page = new Page<String>();
		PrintWriter out = null;
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			input = reconciliationFile.getInputStream();
			ImportExcelEntity entity= new ImportExcelEntity();
			if ("0000000001".equals(calDefId)){//天数excel处理
				entity.setColumnName("days,premRate");
				entity.setColumnValidateRule("2,2");
				entity.setExtraValidateRule("20_0_");
			}else if("0000000003".equals(calDefId)){//月数excel处理
				entity.setColumnName("months,premRate");
				entity.setColumnValidateRule("2,2");
				entity.setExtraValidateRule("20_0_");
			}else if("0000000006".equals(calDefId)){
				if("000000000602".equals(childCalDefId) || "000000000603".equals(childCalDefId)){//驾乘险每座、整车excel处理
					entity.setColumnName("COND7,COND1,PREM_RATE");
					entity.setColumnValidateRule("1,7,2");
					entity.setExtraValidateRule("20_0_1_");
				}else if("000000000605".equals(childCalDefId)){//驾乘险座位区间excel处理
					entity.setColumnName("COND7,COND1,COND2,PREM_RATE");
					entity.setColumnValidateRule("1,2,2,2");
					entity.setExtraValidateRule("20_0_1_");
				}else{
					throw new AppException("excel与算法定义不匹配");
				}
			}else{
				throw new AppException("excel与算法定义不匹配");
			}
			List<Map<String,Object>> excelLists = importExcelBuilderTool.parseExcel(input, entity);
			if(excelLists != null && excelLists.size()>0){
				Map<String, Object> dataMap = new HashMap<String, Object>();
				//驾乘险车辆使用性质特殊处理
				if ("0000000006".equals(calDefId)) {
					String cond7;
					String cond7Error = "";
					for(int i=0; i<excelLists.size(); i++){
						cond7 = excelLists.get(i).get("COND7").toString();
						if(cond7.replaceAll(",", "").replaceAll("\\d", "").length()!=0){
							cond7Error += "第"+(i+2)+"行车辆使用性质有误<br/>";
						}
						if(cond7.contains(",")){
							excelLists.get(i).put("COND7", ","+cond7+",");
						}
						String COND7STR = changeCond7CodeToName(cond7);
						if(COND7STR.length()!=COND7STR.replaceAll("\\d", "").length()){
							cond7Error += "第"+(i+2)+"行车辆使用性质有误<br/>";
						}
						excelLists.get(i).put("COND7STR", COND7STR);
					}
					if(!"".equals(cond7Error)) throw new AppException(cond7Error);
				} 
				TradProdInst tradProdInst = iGatewayProductService.queryTradProdInstById(tradProdCode);
				dataMap.put("tradProdInst", tradProdInst);
				dataMap.put("feeList", excelLists);
				page.setMap(dataMap);
			}else{
				//抛出异常 excel为空
				page.setResult("error");
				page.setMessage("Excel内容为空，请录入数据");
			}		
		} catch (AppException a) {
			logger.info("---------Excel导入失败");
			page.setResult("error");
			page.setMessage(a.getMessage());
		}catch (Exception e) {
			logger.info("---------Excel导入失败");
			page.setResult("error");
			page.setMessage(e.getMessage());
		}finally {
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}

	/**
	 * 查询所有的车辆使用性质
	 * @param tradProdCode
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/queryUseNatureByPage")
	public Page<DictDto> queryUseNatureByPage(int pageIndex) throws Exception {
		List<DictDto> dicList = DictCache.getDict(Constants.DICT_CAR_USE_NATURE);
		Page<DictDto> page = new Page<DictDto>();
		page.setSize(100);// 每页显示条数
		page.setCurrent(pageIndex);// 当前页
		page.setTotal(100);// 总记录数
		page.setData(dicList);
		return page;
	}
	/**
	 * 查询所有的车辆使用性质
	 * @param tradProdCode
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/queryUseNatureByPage1")
	public Page<DictDto> queryUseNatureByPage1(int pageIndex) throws Exception {
		List<DictDto> dicList = DictCache.getDict(Constants.DICT_NLIFE_USERNATRUE);
		Page<DictDto> page = new Page<DictDto>();
		page.setSize(100);// 每页显示条数
		page.setCurrent(pageIndex);// 当前页
		page.setTotal(100);// 总记录数
		page.setData(dicList);
		return page;
	}
	/**
	 * 将车辆使用性质从code转换成name
	 * 非营业客车:602057111,营业客车:602057112,营业货车:602057113,非营业货车:602057114
	 * @param cond7
	 * @return
	 * @throws Exception
	 */
	private String changeCond7CodeToName(String cond7) throws Exception{
		List<DictDto> dicList = DictCache.getDict(Constants.DICT_CAR_USE_NATURE);
		for(DictDto dictDto : dicList){
			cond7 = cond7.replaceAll(dictDto.getCode(), dictDto.getCodeName());
		}
		if(cond7.startsWith(",")){
			cond7 = cond7.substring(1);
		}
		if(cond7.endsWith(",")){
			cond7 = cond7.substring(0, cond7.length()-1);
		}
		return cond7;
	}
	/**
	 * 将车辆使用性质从code转换成name
	 * 非营业客车:602057111,营业客车:602057112,营业货车:602057113,非营业货车:602057114
	 * @param cond7
	 * @return
	 * @throws Exception
	 */
	private String changeCond7CodeToName1(String cond7) throws Exception{
		List<DictDto> dicList = DictCache.getDict(Constants.DICT_NLIFE_USERNATRUE);
		for(DictDto dictDto : dicList){
			cond7 = cond7.replaceAll(dictDto.getCode(), dictDto.getCodeName());
		}
		if(cond7.startsWith(",")){
			cond7 = cond7.substring(1);
		}
		if(cond7.endsWith(",")){
			cond7 = cond7.substring(0, cond7.length()-1);
		}
		return cond7;
	}
	/**
	 * 检验算法对应的方案是否出单
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/checkOpenCalDiv")
	public int checkOpenCalDiv(String prodCode) throws Exception{
		return feeRateService.checkOpenCalDiv(prodCode);
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/queryXBTFeeRate")
	public Map<String,Object> queryXBTFeeRate(String prodCode , String riskCode , String covId ,String deptCodeInfo,String deptNameInfo,String rationId ){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("riskCode", riskCode);
		map.put("coveCode", covId);
		map.put("prodCode", prodCode);
		map.put("rationId", rationId);
		if(deptNameInfo != ""&& deptNameInfo != null){
			map.put("deptName", "%"+deptNameInfo+"%");
		}
		if(deptCodeInfo != "" && deptCodeInfo != null){
			map.put("deptCode", "%"+deptCodeInfo+"%");
		}
		try {
			 List<TradeFeeCov> list= tradeFeeCovService.getTradeFeeCov(map);
			 /**麻醉类型*/
			 List<DictDto> dictDtos= DictCache.getDict(Constants.DICT_NLIFE_ELECODETYPE);
			 /**车辆类型*/
			 List<DictDto> dictDtos1= DictCache.getDict(Constants.DICT_NLIFE_CARTYPE);
			 /**算法规则*/
			 List<DictDto> dictDtos2= DictCache.getDict(Constants.DICT_CALL_TYPE);
			
				 for (int i = 0; i < list.size(); i++) {
					 list.get(i).setPremRate(list.get(i).getPremRate().multiply(new BigDecimal(1000)));
				} 
			
			 map.put("calls", list);
			 map.put("codeCnames",dictDtos);
			 map.put("carType", dictDtos1);
			 map.put("callTypes", dictDtos2);
			 /**配置的产品信息*/
			NlifeProd tradProdInst = nProductService.queryProdInfoById(prodCode);
			map.put("tradProd", tradProdInst);
		} catch (Exception e) {
			logger.error("异常，请联系管理员", e);
		}
		return map;
	}
	
	@ResponseBody
	@RequestMapping(value = "/deletThisCal")
	public Result deletThisCal(String id) throws Exception{
		feeRateService.deletThiscal(id);
		return Result.success("已删除");
	}
	@ResponseBody
	@RequestMapping(value = "/updateThisCal")
	public Result updateThisCal(String prodCode,String riskCode,String id,double premRate,String unused,String covCode,String cond1,String cond2,String cond3,String cond7,String cond10,String cond13,String rationId) throws Exception{
		feeRateService.updateThisCal(prodCode,riskCode,id,covCode,cond1,cond2,cond3,cond7,cond10,cond13,premRate,unused,rationId);
		return Result.success("已更新");
	}
	@ResponseBody
	@RequestMapping(value = "/insertThisCal")
	public Result insertThisCal(String prodCode,String riskCode,double premRate,String unused,String covCode,String cond1,String cond2,String cond3,String cond7,String cond10,String cond13,String rationId) throws Exception{
		Map<String , Object> map = new HashMap<String, Object>();
		map.put("prodCode", prodCode);
		map.put("riskCode", riskCode);
		map.put("covCode", covCode);
		if(cond1==null){
			cond1="";
		}
		map.put("cond1", cond1);
		if(cond2==null){
			cond2="";
		}
		map.put("cond2", cond2);
		map.put("cond3", cond3);
		map.put("cond7", cond7);
		map.put("cond10", cond10);
		map.put("cond13", cond13);
		map.put("premRate", premRate/1000);
		
		map.put("unused", unused);
		map.put("rationId", rationId);
		if(this.isExistCal(cond7, prodCode, covCode, cond10,cond1,cond2,cond3).get("isExist") == "true"){
			return Result.fail("已存在的责任");
		}
		feeRateService.insertThisCal(map);
		return Result.success("已添加");
	}
	
	@RequestMapping(value = "/backToProductConfig")
	public String XBTInsureEditRequest(ModelMap model,String prodCode,String riskCode,String covId)throws Exception{
		model.put("isBack", true);
		model.put("prodCode", prodCode);
		return "nlifeProduct/productConfig/list";
	}
	
	@ResponseBody
	@RequestMapping(value = "isExistCal")
	public Map<String,String> isExistCal(String cond7,String prodCode,String covCode,String cond10,String cond1,String cond2,String cond3) throws Exception{
		//以机构代码、产品代码、责任代码、需求类型作为条件查ID，如果ID不为空，则该责任已经存在，返回
		//isExist = true ，ID = 查到的ID  insert逻辑变成update逻辑；
		//否则继续insert
		
		
		/*20190507新增：当选择算法为 年区间算法 时，不能单以以上的条件进行判断
		 * 逻辑：	1、判断是否为年区间（value=3）
		 * 		2、当为年区间时，除以上条件外，再加条件：cond1 、 cond2 在已有的范围内,返回true；
		 * */
		Map<String, String> map = new HashMap<String, String>();
		map.put("prodCode", prodCode);
		map.put("covCode", covCode);
		map.put("cond7", cond7);
		map.put("cond10", cond10);
		String id = feeRateService.isExistCal(map);
		Map<String, String> rsmap = new HashMap<String, String>();
		
		if(id != null && !cond3.equals("3")){
			//当存在一条数据且不是年区间， 存在已有数据
			rsmap.put("isExist", "true");
			rsmap.put("id", id);
			return rsmap;
		}else if(id == null){
			//当不存在数据，直接返回
			rsmap.put("isExist", "false");
			return rsmap;
		}else if(id != null && cond3.equals("3")){
			
			int max = Integer.parseInt(cond2);
			int min = Integer.parseInt(cond1);
			//当存在数据但是是年区间
			//查所有该产品该责任的算法（应该全是年区间）
			//返回的是List<Map<String,Object>>,长度List.length是存在的算法条数
			List<Map<String,BigDecimal>> rsListUse3 =  feeRateService.queryCovUse3(map);
			
			//for循环判断是否有该区间的算法（区间重叠）
			boolean flag = true;
			for (Iterator iterator = rsListUse3.iterator(); iterator.hasNext();) {
				Map<String, BigDecimal> map2 = (Map<String,BigDecimal>) iterator.next();
				if(!map2.get("COND3").toString().equals("3")){
					//这种情况是查出来该责任下以前配过非年区间的算法
					rsmap.put("isExist", "true");
					rsmap.put("id", id);
					return rsmap;
				}
				String minStr = map2.get("COND1").toString();
				String maxStr = map2.get("COND2").toString();
				

				int thisMin = Integer.parseInt(minStr);
				int thisMax = Integer.parseInt(maxStr);
				//最大值小于最小值、最小值大于最大值，未重叠
				if(min >= thisMax || max <= thisMin){
					continue;
				}else{
					flag = false;
				}
			}
			if(flag == true){
				//没有该区间的算法；
				rsmap.put("isExist", "false");
				return rsmap;
			}else{
				//存在该区间的算法
				rsmap.put("isExist", "true");
				rsmap.put("id", id);
				return rsmap;
			}
		}else{
			rsmap.put("isExist", "false");
			return rsmap;
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/insertOrUpdateShortRate")
	public Result insertOrUpdateShortRate(String prodCode,String riskCode,String deptCode,String shortRate,String xbtFlag,String covCode,String rationId) throws Exception{
			//两种情况 ，简单点做一种处理：先删除再新增，提高效率；
			Map<String,String> map = new HashMap<String, String>();
			map.put("prodCode", prodCode);
			map.put("riskCode", riskCode);
			map.put("deptCode", deptCode);
			map.put("shortRate", shortRate);
			map.put("xbtFlag", xbtFlag);
			map.put("covCode", covCode);
			map.put("rationId", rationId);
			
			
			//查询现有符合条件的条数：
			int count = feeRateService.queryExistShortRateByMap(map);
			if(count > 1){
				return Result.error("系统中有多条短期费率配置，请联系管理员处理！");
			}else {
				//已配置短期费率或未配置短期费率，对该行数据进行更新
				feeRateService.updateShortRate(map);
			}
			
		return Result.success("保存成功");
	}
	
	@ResponseBody
	@RequestMapping(value = "/writeBackShortRate")
	public Result writeBackShortRate(String prodCode , String riskCode,String covCode , String deptCode,String xbtFlag) throws Exception{
		//短期费率回写
		Map<String,String> map = new HashMap<String, String>();
		map.put("prodCode", prodCode);
		map.put("riskCode", riskCode);
		map.put("covCode", covCode);
		map.put("deptCode", deptCode);
		map.put("xbtFlag", xbtFlag);
		String shortRateStr = feeRateService.writeBackShortRate(map);
		
		if(shortRateStr == null || shortRateStr.equals("")){
			return Result.fail();
		}else{
			String[] reslut = shortRateStr.split("\\|");
			if(reslut.length == 12){
				return Result.success(reslut);
			}else{
				return Result.fail();
			}
			
		}
	}
	
}